package spring.mvc.dao;

import java.util.List;

import javax.persistence.EntityManager;

import org.apache.log4j.Logger;

import spring.mvc.bean.Person;
import spring.mvc.util.JPAUtil;

public class PersonDaoImpl implements PersonDao {
	protected static Logger logger = Logger.getLogger("dao");
	@Override
	public Person getByName(String name) {
		Person p = new Person();
		PersonDaoImpl dao = new PersonDaoImpl();
		try {
			List<Person> list = dao.getList();
			for (Person person : list) {
				if (person.getName().equals(name)) {
					logger.debug("User found");
					p = person;
					break;
				}
			}
		} catch (Exception e) {
			p = null;
			logger.error("User does not exist!");
		}
		return p;
	}

	@SuppressWarnings("unchecked")
	public List<Person> getList() {
		EntityManager em = JPAUtil.getEntityManager();
		em.getTransaction().begin();
		List<Person> list = em.createQuery("from Person").getResultList();
		em.getTransaction().commit();
		em.close();
		return list;
	}

	public void addUser(Person user) {
		EntityManager manager = JPAUtil.getEntityManager();
		manager.getTransaction().begin();
		manager.persist(user);
		manager.getTransaction().commit();
		manager.close();

	}

}
